const express = require('express')
const router = express.Router()
const multer = require('multer')
const path = require('path')
const fs = require('fs')
const { adminAuth } = require('@middlewares/auth')
const { ApiResponse } = require('@shared/utils/response')
const uploadController = require('@controllers/admin/upload.controller')
const { uploadImage, uploadFile } = require('@shared/utils/upload')
const logger = require('@shared/utils/logger')

console.log('admin upload route loaded')
logger.debug('admin upload route loaded')

// 配置上传目录
const UPLOAD_DIR = path.join(__dirname, '../../../public/uploads')

// 确保上传目录存在
if (!fs.existsSync(UPLOAD_DIR)) {
  fs.mkdirSync(UPLOAD_DIR, { recursive: true })
  logger.info(`创建上传目录: ${UPLOAD_DIR}`)
}

// 配置 multer 存储
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, UPLOAD_DIR)
  },
  filename: function (req, file, cb) {
    // 生成文件名: 时间戳 + 随机数 + 原始扩展名
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
    cb(null, uniqueSuffix + path.extname(file.originalname))
  }
})

// 文件过滤器
const fileFilter = (req, file, cb) => {
  // 允许的文件类型
  const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
  
  if (allowedTypes.includes(file.mimetype)) {
    cb(null, true)
  } else {
    cb(new Error('不支持的文件类型'), false)
  }
}

const upload = multer({
  storage: storage,
  fileFilter: fileFilter,
  limits: {
    fileSize: 5 * 1024 * 1024 // 限制5MB
  }
})

// 单图片上传
router.post('/image', adminAuth, (req, res, next) => {
  logger.debug('接收到 /image 路径的上传请求')
  logger.debug('请求体:', req.body)
  next()
}, uploadImage.single('image'), uploadController.uploadImage)

// 单文件上传
router.post('/file', adminAuth, (req, res, next) => {
  logger.debug('接收到 /file 路径的上传请求')
  next()
}, uploadFile.single('file'), uploadController.uploadFile)

// 直接对根路径的上传请求也处理为图片上传（兼容旧接口）
router.post('/', adminAuth, (req, res, next) => {
  logger.debug('接收到根路径的上传请求')
  logger.debug('请求体:', req.body)
  next()
}, uploadImage.single('image'), uploadController.uploadImage)

// 多文件上传，最多5个文件
router.post('/multiple', adminAuth, uploadImage.array('files', 5), (req, res) => {
  try {
    if (!req.files || req.files.length === 0) {
      return res.json(ApiResponse.error('请选择要上传的文件'))
    }

    // 构建访问URL
    const baseUrl = process.env.NODE_ENV === 'production'
      ? process.env.API_BASE_URL || 'https://api.example.com'
      : `http://localhost:${process.env.PORT || 3001}`;

    // 返回所有文件信息
    const filesInfo = req.files.map(file => ({
      url: `${baseUrl}/public/uploads/images/${file.filename}`,
      path: `/public/uploads/images/${file.filename}`,
      name: file.originalname,
      size: file.size,
      type: file.mimetype
    }))

    res.json(ApiResponse.success(filesInfo))
  } catch (error) {
    res.json(ApiResponse.error(error.message))
  }
})

// 错误处理中间件
router.use((error, req, res, next) => {
  logger.error('上传错误:', error)
  
  if (error instanceof multer.MulterError) {
    // multer 错误
    if (error.code === 'LIMIT_FILE_SIZE') {
      logger.warn('文件大小超出限制')
      return res.json(ApiResponse.error('文件大小超出限制'))
    }
    logger.warn('Multer错误:', error.code, error.message)
    return res.json(ApiResponse.error(error.message))
  }
  
  // 其他错误
  logger.error('未知上传错误:', error)
  res.json(ApiResponse.error(error.message))
})

router.all('*', (req, res) => {
  logger.warn('[upload.route] upload 路由未命中:', req.method, req.originalUrl)
  console.log('[upload.route] upload 路由未命中:', req.method, req.originalUrl)
  res.status(404).json({ code: 404, message: 'upload 路由未命中' })
})

module.exports = router 